<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formClassAIRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormClassAI()" @reset="resetFormClassAI">
        <el-form-item label="班级名称">
          <el-input
            class="filter-item"
            v-model="formFilter.classNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="班级级别">
          <el-select
            class="filter-item"
            v-model="formFilter.classLevelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="classLevelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in classLevelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区">
          <dept-select
            class="filter-item"
            v-model="formFilter.schoolIdFilter"
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            class="filter-item"
            v-model="formFilter.createTimeFilter"
            type="daterange"
            start-placeholder=""
            end-placeholder=""
            :clearable="true"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date().setHours(0, 0, 0, 0), new Date().setHours(23, 59, 59, 999)]"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="studentClass"
      class="page-table"
      :data="studentClassWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((studentClassWidgetCurrentPage - 1) * studentClassWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      rowKey="classId"
      :inlineRules="studentClassInline.inlineRules"
      @sort-change="studentClassWidget.onSortChange"
      @refresh="studentClassWidget.refreshTable()"
      @change="onStudentClassSelectionChange"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddStudentclassClick()"
          >
          行内添加
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onFormAddClassAIClick()"
          >
          新建班级
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportClick()"
          >
          导出
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onBatchDeleteClick()"
          >
          批量删除
        </el-button>
      </template>
      <vxe-column fixed="left" type="checkbox" :width="40" />
      <vxe-column title="序号" type="seq" fixed="left" :index="studentClassWidget.getTableIndex" :width="80" />
      <table-box-inline-input-column
        ref="studentClassClassName"
        title="班级名称"
        field="className"
        :clearable="true"
        size="default"
      >
      </table-box-inline-input-column>
      <table-box-inline-cascader-column
        ref="studentClassSchoolId"
        title="所属校区"
        field="schoolId"
        :clearable="true"
        size="default"
        :multiple="false"
        :loadDropdownData="loadStudentClassSchoolIdDropdownData"
      >
        <template v-slot="scope">
          <span>{{ (scope.row.schoolIdDictMap || {}).name }}</span>
        </template>
      </table-box-inline-cascader-column>
      <table-box-inline-select-column
        ref="studentClassClassLevel"
        title="班级级别"
        field="classLevel"
        :clearable="true"
        size="default"
        :multiple="false"
        :loadDropdownData="loadStudentClassClassLevelDropdownData"
      >
        <template v-slot="scope">
          <el-tag size="default" type="primary">{{ (scope.row.classLevelDictMap || {}).name }}</el-tag>
        </template>
      </table-box-inline-select-column>
      <table-box-inline-number-column
        ref="studentClassFinishClassHour"
        title="完成课时"
        field="finishClassHour"
        :clearable="true"
        size="default"
      >
      </table-box-inline-number-column>
      <table-box-inline-date-column
        ref="studentClassCreateTime"
        title="创建时间"
        field="createTime"
        :clearable="true"
        size="default"
        type="date"
        format="YYYY-MM-DD HH:mm:ss"
        valueFormat="YYYY-MM-DD HH:mm:ss"
      >
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.createTime, 'day')}}</span>
        </template>
      </table-box-inline-date-column>
      <table-box-inline-auto-save-column
        v-if="studentClassInline.supportAutoNext"
        @save="row => onSaveStudentClassInlineRow(row, true)"
      />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <template v-if="!studentClass.isRowEditing(scope.row)">
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onEditStudentclassClick(scope.row)"
              :disabled="studentClass.isTableEditing()"
            >
              行内编辑
            </el-button>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onDeleteClick(scope.row)"
              :disabled="studentClass.isTableEditing()"
            >
              删除
            </el-button>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onFormEditClassAIClick(scope.row)"
              :disabled="studentClass.isTableEditing()"
            >
              编辑班级
            </el-button>
          </template>
          <template v-else>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              key="studentClassSaveTable"
              @click.stop="onSaveStudentClassInlineRow(scope.row, false)"
            >
              保存
            </el-button>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              key="studentClassSaveTable"
              @click.stop="onCancelStudentClassInlineRow(scope.row)"
            >
              取消
            </el-button>
          </template>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="studentClassWidgetTotalCount"
            :current-page="studentClassWidgetCurrentPage"
            :page-size="studentClassWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="studentClassWidget.onCurrentPageChange"
            @size-change="studentClassWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formClassAI',
};
</script>

<script setup lang="ts">
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { StudentController, StudentClassController, CourseController, SysDeptController } from '@/api/generated';
import FormEditClassAI from '@/pages/aiform/formEditClassAI.vue';
import FormAddClassAI from '@/pages/aiform/formAddClassAI.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 班级名称
  classNameFilter: undefined,
  // 班级级别
  classLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
  // 创建时间
  createTimeFilter: [],
});
const formFilterCopy = reactive({
  // 班级名称
  classNameFilter: undefined,
  // 班级级别
  classLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
  // 创建时间
  createTimeFilter: [],
});
// 表格行内编辑用到的所有字典数据
const inlineTableDictList = ref({
  classLevelDataList: [],
  sysDeptDataList: [],
});
const instance = getCurrentInstance();

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormClassAI();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadStudentClassWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    studentClassDtoFilter: {
      className: formFilter.classNameFilter,
      schoolId: formFilter.schoolIdFilter,
      classLevel: formFilter.classLevelFilter,
      createTimeStart: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[0] : formFilter.createTimeFilter,
      createTimeEnd: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[1] : formFilter.createTimeFilter,
    }
  };
  return new Promise((resolve, reject) => {
    StudentClassController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentClassVerify = () => {
  formFilterCopy.classNameFilter = formFilter.classNameFilter;
  formFilterCopy.classLevelFilter = formFilter.classLevelFilter;
  formFilterCopy.schoolIdFilter = formFilter.schoolIdFilter;
  formFilterCopy.createTimeFilter = formFilter.createTimeFilter;
  return true;
};
/**
 * 批量删除
 */
const onStudentClassSelectionChange = (values) => {
  studentClassBatchSelectRows.value = values || [];
};
const onAddStudentclassClick = () => {
  // 新建行内编辑数据
  const newRow = {
    // 班级Id
    classId: undefined,
    // 班级名称
    className: undefined,
    // 所属校区
    schoolId: undefined,
    // 班长
    leaderId: undefined,
    // 完成课时
    finishClassHour: undefined,
    // 班级级别
    classLevel: undefined,
    // 创建用户
    createUserId: undefined,
    // 班级创建时间
    createTime: undefined,
    // 班级状态(0: 正常 1: 解散)
    status: undefined,
  };
  studentClass.value.editRow(newRow, true);
  if (studentClassClassName.value != null && studentClassClassName.value.focus != null) {
    nextTick(() => {
      studentClassClassName.value.focus();
    });
  }
};
/**
 * 新建班级
 */
const onFormAddClassAIClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建班级', FormAddClassAI, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      studentClassWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导入
 */
const onImportClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  StudentClassController.import(params).then(res => {
    ElMessage.success('导入成功');
    studentClassWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 导出
 */
const onExportClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    studentClassDtoFilter: {
      className: formFilter.classNameFilter,
      schoolId: formFilter.schoolIdFilter,
      classLevel: formFilter.classLevelFilter,
      createTimeStart: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[0] : formFilter.createTimeFilter,
      createTimeEnd: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[1] : formFilter.createTimeFilter,
    }
  };

  StudentClassController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
const onEditStudentclassClick = (row?: StudentClassData) => {
  if (row == null) return;
  studentClass.value.editRow(row, false);
  if (studentClassClassName.value != null && studentClassClassName.value.focus != null) {
    nextTick(() => {
      studentClassClassName.value.focus();
    });
  }
};
/**
 * 删除
 */
const onDeleteClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    classId: row?.classId,
  };

  ElMessageBox.confirm('是否删除此班级？').then(res => {
    StudentClassController.delete(params).then(res => {
      ElMessage.success('删除成功');
      studentClassWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 批量删除
 */
const onBatchDeleteClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
  };

  ElMessageBox.confirm('是否删除选中数据？').then(res => {
    params.classIdList = studentClassBatchSelectRows.value.map(item => item.classId);
    StudentClassController.deleteBatch(params).then(res => {
      ElMessage.success('删除成功');
      studentClassBatchSelectRows.value = [];   
      studentClassWidget.refreshTable(true, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 编辑班级
 */
const onFormEditClassAIClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    classId: row?.classId,
  };

  router.push({
    name: 'formEditClassAI',
    query: { ...params, subPage: true }
  });
};
const loadStudentClassSchoolIdDropdownData = (row?: StudentClassData) => {
  let temp = inlineTableDictList.value.sysDeptDataList;
  return Promise.resolve(temp);
};
const loadStudentClassClassLevelDropdownData = (row?: StudentClassData) => {
  let temp = inlineTableDictList.value.classLevelDataList;
  return Promise.resolve(temp);
};
const mergeStudentClassInlineRow = (row, rowCopy) => {
  row.className = rowCopy.className;
  row.schoolId = rowCopy.schoolId;
  row.schoolIdDictMap = rowCopy.schoolIdDictMap || {};
  row.classLevel = rowCopy.classLevel;
  row.classLevelDictMap = rowCopy.classLevelDictMap || {};
  row.finishClassHour = rowCopy.finishClassHour;
  row.createTime = rowCopy.createTime;
};
const onSaveStudentClassInlineRow = (row, autoEditNext) => {
  if (studentClass.value != null) {
    studentClass.value
      .saveRow(autoEditNext)
      .then(res => {
        let { rowData, nextRow, isNew, isDirty } = res;
        let params = {
          studentClassDto: {
            ...rowData
          }
        };
        if (isNew) {
          // 新建数据
          StudentClassController.add(params)
            .then(res => {
              ElMessage.success('保存成功');
              studentClassWidget.refreshTable(false);
            })
            .catch(e => {
              if (studentClassClassName.value != null && studentClassClassName.value.focus != null) {
                nextTick(() => {
                  studentClassClassName.value.focus();
                });
              }
            });
          return;
        }
        if (!isNew) {
          // 保存数据
          if (!isDirty) {
            // 未修改数据
            if (autoEditNext) {
              if (nextRow == null) {
                nextRow = studentClassWidgetDataList[0];
              }
              onEditStudentclassClick(nextRow);
            } else {
              onCancelStudentClassInlineRow(row);
            }
          } else {
            // 行数据已经修改
            StudentClassController.update(params)
              .then(res => {
                ElMessage.success('保存成功');
                studentClassWidget.refreshTable(false);
              })
              .catch(e => {
                if (studentClassClassName.value != null && studentClassClassName.value.focus != null) {
                  nextTick(() => {
                    studentClassClassName.value.focus();
                  });
                }
              });
          }
        }
      })
      .catch(e => {
        if (e != null) {
          if (e != null && e.message != null && e.message !== '') {
            const firstField = 'studentClass' + stringCase(e.message, 1);
            const proxy = instance?.proxy;
            if (proxy != null) {
              if (proxy.$refs[firstField] && proxy.$refs[firstField].focus != null) proxy.$refs[firstField].focus();
            }
          }
        }
      });
  }
};
const onCancelStudentClassInlineRow = (row, deleteRow = true) => {
  if (studentClass.value != null) {
    studentClass.value.cancelEditRow(deleteRow);
  }
};
// 表格组件表格组件参数
const studentClassOptions: TableOptions<StudentClassData> = {
  loadTableData: loadStudentClassWidgetData,
  verifyTableParameter: loadStudentClassVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'createTime',
  ascending: true,
};
// 批量选中数据
const studentClassBatchSelectRows = ref<StudentClassData[]>([]);
const studentClassInline = ref({
  // 行内编辑校验规则
  inlineRules: {
    'className': [
      {required: true, message: '请输入班级名称', trigger: 'blur'}
    ],
    'schoolId': [
      {required: true, message: '请输入所属校区', trigger: 'blur'}
    ],
    'classLevel': [
      {required: true, message: '请输入班级级别', trigger: 'blur'}
    ],
    'finishClassHour': [
      {required: true, message: '请输入完成课时', trigger: 'blur'},
      {type: 'integer', message: '完成课时只允许输入整数', trigger: 'blur', transform: (value) => Number(value)},
      {type: 'number', min: 0, message: '完成课时必须大于0', trigger: 'blur', transform: (value) => Number(value)},
    ],
    'createTime': [
    ],
  },
  // 是否支持自动编辑下一行
  supportAutoNext: true
});
// 行内编辑列录入组件引用
const studentClassClassName = ref(null);
const studentClassSchoolId = ref(null);
const studentClassClassLevel = ref(null);
const studentClassFinishClassHour = ref(null);
const studentClassCreateTime = ref(null);
// 表格组件表格组件
const studentClass = ref();
const studentClassWidget = useTable(studentClassOptions);
const {
  dataList: studentClassWidgetDataList,
  currentPage: studentClassWidgetCurrentPage,
  pageSize: studentClassWidgetPageSize,
  totalCount: studentClassWidgetTotalCount,
} = studentClassWidget;
/**
 * 班级级别下拉数据获取函数
 */
const loadClassLevelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 班级级别配置参数
const classLevelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadClassLevelFilterDropdownList,
  isTree: false,
};
// 班级级别下拉组件
const classLevelFilterWidget = useDropdown(classLevelFilterOptions);
const { dropdownList: classLevelFilterWidgetDropdownList } = classLevelFilterWidget
const refreshFormClassAI = () => {
  // 刷新段落
  studentClassWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormClassAI = () => {
  formFilter.classNameFilter = undefined;
  formFilterCopy.classNameFilter = undefined;
  formFilter.classLevelFilter = undefined;
  formFilterCopy.classLevelFilter = undefined;
  formFilter.schoolIdFilter = undefined;
  formFilterCopy.schoolIdFilter = undefined;
  formFilter.createTimeFilter = undefined;
  formFilterCopy.createTimeFilter = undefined;
  refreshFormClassAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormClassAI();
};
const loadInlineClassLevelData = () => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'String' }).then(res => {
      inlineTableDictList.value.classLevelDataList = res.getList();
      inlineTableDictList.value.classLevelDataList.forEach(item => {
        item.id = item.id.toString();
        if (item.parentId) item.parentId = item.parentId.toString();
      });
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
const loadInlineSysDeptData = () => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictSysDept({}).then(res => {
      inlineTableDictList.value.sysDeptDataList = res.getList();
      inlineTableDictList.value.sysDeptDataList.forEach(item => {
        item.id = item.id.toString();
        if (item.parentId) item.parentId = item.parentId.toString();
      });
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
const loadAllInlineTableDictData = () => {
  return new Promise((resolve, reject) => {
    let promises = [
      loadInlineClassLevelData(),
      loadInlineSysDeptData(),
    ];
    Promise.all(promises).then(() => {
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
const formInit = () => {
  classLevelFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormClassAI();
};

onMounted(() => {
  loadAllInlineTableDictData().then(() => {
    formInit();
  }).catch(() => {
    formInit();
  });
});

onActivated(() => {
  onResume();
});
</script>